#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <iostream>
#include <string.h>
#include <vector>
#define N 10

int main()
{
    std::vector<pid_t> subids;
    int i = 0;
    for(; i < N ; i++)
    { 
        pid_t id = fork();
        if(id == 0)
        {
            int i = 3;
            while(1)
            {
                printf("我是一个子进程, pid = %d, ppid = %d, count: %d\n", getpid(), getppid(), i);
                sleep(3);
                //int a = 10;
                //a /= 0;
                //野指针
                int* p = NULL;
                *p = 100;
                sleep(1);
                i--;
            }

            printf("子进程退出!\n");
            int ret = 1;
            if(ret == 0)
              exit(0);
            else
              exit(1);
        }
        subids.push_back(id);
    } 
    sleep(5);
    for(auto& sid : subids)
    {
       //pid_t rid = wait(NULL);
        int status = 0;
        printf("父进程等待子进程退出,子进程pid: %d\n", sid);
        pid_t rid = waitpid(sid, &status, 0);
        if(rid > 0)
        {
            int exit_code = (status >> 8) & 0xFF;
            int exit_signal = status & 0x7F;
            if(exit_code == 0 && exit_signal ==0)
            {
                printf("子进程运行完毕，结果正确!\n");
            }
            else if(exit_code != 0 && exit_signal == 0)
            {
                printf("子进程运行完毕，结果不正确: %d:%s\n", exit_code, strerror(exit_code));
            }
            else if(exit_signal > 0)
            {
                printf("子进程运行异常,exit_signal: %d\n", exit_signal);
            }
            //printf("父进程等待子进程成功，子进程pid: %d, status: %d, exit code: %d, exit signal: %d\n",
             //   rid, status, exit_code, exit_signal);
        }
        else{
          printf("wait failed\n");
        }
    }





















    //usrid_t id = fork();
    //if(id == 0)
    //{
    //    int i = 10;
    //    while(i)
    //    {
    //        printf("我是一个子进程, pid = %d, ppid = %d, count: %d\n", getpid(), getppid(), i);
    //        sleep(1);
    //        i--;
    //    }
    //    printf("子进程退出!\n");
    //    exit(1);
    //}
    //
    //sleep(15);
    //printf("父进程等待子进程退出\n");
    //pid_t rid = wait(NULL);
    //if(rid > 0)
    //{
    //    printf("父进程等待子进程成功，子进程pid: %d\n", rid);
    //    sleep(5);
    //}
    return 0;
}
